package hbr.vedio.x163;

import hbr.vedio.V;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class X163 {

	String ua = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36";

	public V go(String url) throws Exception {
		V v = new V();

		int i = 0;
		while (true) {
			try {
				Connection conn = Jsoup.connect(url);
				Document doc = conn.get();

				v.title = doc.select(".m-cdes h2").text();
				// v.cover = doc.select(".m-cintro img").attr("src");

				Elements es = doc.select("#list1 tr .u-ctitle");

				v.eps = es.size();

				v.content = doc.select(".m-cdes p").outerHtml();
				v.content += doc.select(".picText h6").outerHtml(); // clean -r
				v.content += doc.select(".cContent").html();

				v.list = "";

				for (Element e : es) {
					String eurl = e.select("a").attr("href");
					// System.out.println(eurl);
					String x_name = e.text();
					v.list += x_name + "|" + one(eurl) + "\n";
				}
				break;
			} catch (Exception e) {
				if (i++ > 3) {
					throw e;
				}
			}
		}
		return v;
	}

	// return url|size
	private String one(String url) throws Exception {
		Connection conn = Jsoup.connect(url);
		Document doc = conn.get();

		// swf.ws.126.net
		String html = doc.html();
		for (String l : StringUtils.split(html, "\n")) {
			if (l.contains("swf.ws.126.net")) {
				l = l.trim();
				l = l.substring(l.indexOf("'") + 1, l.lastIndexOf("'"));
				// System.out.println(l);
				return l;
			}
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		String url = "http://v.163.com/special/opencourse/hegel.html";
		new X163().go(url);
	}
}